package com.zdd.chap2.controller;

import com.zdd.chap2.vo.ResultVo;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 多文件上传
 */
@RestController
public class FilesUploadController {
    @Value("${web.upload-path}")
    private String uploadPath;
    @PostMapping("/uploads")
    public ResultVo upload(@RequestParam("uploadFiles") MultipartFile[] uploadFiles, HttpServletRequest request){
        System.out.println("aa"+uploadFiles.length);
        if(uploadFiles!=null&&uploadFiles.length>0){
            int i=1;
            for(MultipartFile uploadFile:uploadFiles){
                System.out.println(i);
                i++;
                //获取文件初始名称
                String originalFilename=uploadFile.getOriginalFilename();
                //获取文件后缀名
                String suffix=originalFilename.substring(originalFilename.lastIndexOf(".")+1);
                //判断文件格式
                if(suffix.equalsIgnoreCase("jpg")||suffix.equalsIgnoreCase("jpeg")||suffix.equalsIgnoreCase("png")||suffix.equalsIgnoreCase("gif")){
                    //判断文件上传大小
                    if(uploadFile.getSize()>500*1024){
                        return ResultVo.error("文件大小超过500kb",false);
                    }
                    File file=new File(uploadPath);
                    if(!file.exists()){
                        file.mkdirs();
                    }
                    String filename= UUID.randomUUID().toString().replace("-","");
                    File saveFile=new File(file,filename+"."+suffix);
                    try {
                        uploadFile.transferTo(saveFile);
                    } catch (IOException e) {
                        return ResultVo.error(e.getMessage(),false);
                    }
                }else{
                    return ResultVo.error("文件上传格式不正确",false);
                }
            }
        }else{
            return ResultVo.error("文件上传为空",false);
        }
        return ResultVo.success("文件上传成功",true,null);
    }
}
